import { ref, computed, inject } from 'vue';
import basic from '@common/basic';
import alternativeRuleTools from '@modules/pdm/business-module/part/views/alternative-rule/utils/tools.js';
import { cloneDeep } from 'lodash';
const useOperate = basic.getExportResource('@/basic/components/operate-iteration/js/operate.js').default;
export const createProps = (op = {}) => {
  return {
    // 当前对象
    row: {
      type: Object,
      default: () => ({})
    },
    // 是否有超链接列
    isHyperlinkProp: {
      type: String,
      default: ''
    },
    // 表格标识
    tableTypeRef: {
      type: String,
      default: ''
    },
    ...op
  };
};
export const createEmits = (op = []) => {
  return ['getCurrentRow', 'handleRefreshData', ...op];
};

/* 替代规则列表中行内操作hooks */
export const useTableRowOperate = (props, emits) => {
  const { proxy } = getCurrentInstance();
  const { wujieName } = window.$wujie?.props || {};
  const { handleDeleteCurrentList } = alternativeRuleTools();
  const { operateCommand } = useOperate({ moduleName: `${wujieName}` }, {});
  const isShowBtn = computed(() => {
    return (row, type) => {
      return row.lockstateinfo == type;
    };
  });
  const btnLoadingMap = ref({});
  const editaccessShow = inject('editaccessShow');
  const mainObj = inject('mainObj');
  const btnOptions = computed(() => {
    return (row, type) => {
      let obj = {
        hyperlink: {
          type: 'text',
          iconClass: 'iconfont icon-operation-link1',
          content: proxy.$t('viewDetail')
        },
        checkin: {
          type: 'text',
          iconClass: 'iconfont icon-a-structure-checkin',
          content: proxy.$t('btn.checkin'),
          loading: btnLoadingMap.value['CheckIn']
        },
        checkout: {
          type: 'text',
          iconClass: 'iconfont icon-a-structure-checkout',
          content: proxy.$t('checkOut'),
          loading: btnLoadingMap.value['CheckOut']
        },
        revoke: {
          type: 'text',
          iconClass: 'iconfont icon-structure-revoke',
          content: proxy.$t('btn.revokedcheckout'),
          loading: btnLoadingMap.value['UndoCheckOut']
        },
        edit: {
          type: 'text',
          iconClass: 'iconfont icon-operation-edit1',
          content: proxy.$t('btn.edit'),
          loading: btnLoadingMap.value['edit']
        }
      };
      return obj[type];
    };
  });
  const handleHyperlinkObj = row => {
    let obj = {
      oid: row.oid,
      otype: row.otype,
      identifierDisplayName: row.identifierDisplayName,
      containeroid: row.containeroid,
      containerotype: row.containerotype,
      viewType: 'VIEW',
      path: 'alternativeRuleDetail'
    };
    window.$wujie?.bus.$emit('openAlternativeRuleDetail', obj, wujieName);
  };
  const handleCommonCheckObj = async (list = [], type = '', msgName = '', isLoading = true) => {
    let param = list.map(item => {
      return {
        id: item.oid,
        typeDefName: item.otype
      };
    });
    if (!type) return;
    if (isLoading) btnLoadingMap.value[type] = true;
    let exceptionCallback = () => {
      btnLoadingMap.value[type] = false;
    };
    const res = await proxy.apiFunTools.commandFunc('$pdmapis', 'part', `batchMultiAlternate${type}`, param, {
      needResponseBody: true,
      exceptionCallback
    });
    let data = res.data;
    if (data?.data?.length) {
      if (msgName) proxy.$tyPlmMessage.success(proxy.$t('alternativeRuleSuccess', { name: msgName }));
      let map = getMapByData(data?.data, 'sourceId');
      let i = 0;
      while (list[i]) {
        if (list[i]?.oid && map[list[i].oid]) {
          let originOid = cloneDeep(list[i]?.oid);
          list[i].oid = map[originOid].id;
          list[i].identifierDisplayName = map[originOid].identifierDisplayName;
          list[i].lockstateinfo = map[originOid].checkInOrCheckOut;
          list[i].lockerName = map[originOid].checker || '';
          list[i].lockerFullName = map[originOid].checkerFullName || '';
          list[i].checkoutBy = list[i].lockerFullName ? `${list[i].lockerFullName}(${list[i].lockerName})` : '';
          // modify by gejq 2025/2/14 更新修改者、修改时间
          list[i].updatorDisplayName = map[originOid].updatorDisplayName;
          list[i].modifystamp = map[originOid].modifystamp;
          list[i].displayVersion = map[originOid].displayVersion;
        }
        i++;
      }
    }
    btnLoadingMap.value[type] = false;
  };
  const handleCheckinObj = row => {
    handleCommonCheckObj([row], 'CheckIn', proxy.$t('checkIn'));
  };
  const handleCheckoutObj = async row => {
    await handleCommonCheckObj([row], 'CheckOut', proxy.$t('checkOut'));
  };
  const handleRevokeCheckoutObj = row => {
    handleCommonCheckObj([row], 'UndoCheckOut', proxy.$t('btn.revokedcheckout'));
  };
  const handleEditObj = async row => {
    let flag = isShowBtn.value(row, 'c/i');
    btnLoadingMap.value['edit'] = true;
    if (flag) await handleCommonCheckObj([row], 'CheckOut', proxy.$t('checkOut'), false);
    btnLoadingMap.value['edit'] = false;
    let obj = {
      oid: row.oid,
      otype: row.otype,
      identifierDisplayName: row.identifierDisplayName,
      containeroid: row.containeroid,
      containerotype: row.containerotype,
      viewType: 'UPDATE',
      path: 'alternativeRuleDetail'
    };
    window.$wujie?.bus.$emit('openAlternativeRuleDetail', obj, wujieName);
  };
  const dropdownOptions = computed(() => {
    return row => {
      let btnDisabled = row.lockstateinfo == 'c/i';
      return {
        trigger: 'click',
        list: [
          {
            icon: 'iconfont icon-shezhi',
            label: proxy.$t('basic.permission.setStatus'),
            value: 'status',
            disabled: !btnDisabled || !window.$wujie?.props?.calcResult2('设置状态', [row])
          },
          {
            icon: 'iconfont icon-a-zhongmingming1',
            label: proxy.$t('basic.btn.rename'),
            value: 'rename',
            disabled: !btnDisabled || !window.$wujie?.props?.calcResult2('重命名', [row])
          },
          {
            icon: 'iconfont icon-yonghu',
            label: proxy.$t('setOwner'),
            value: 'owner',
            disabled: !btnDisabled || !window.$wujie?.props?.calcResult2('设置所有者', [row])
          },
          {
            icon: 'iconfont icon-a-liuchengzhong2',
            label: proxy.$t('newProcess'),
            value: 'process',
            disabled: !btnDisabled
          },
          {
            icon: 'iconfont icon-bianjifangwenkongzhiquanxian',
            label: proxy.$t('basic.table.editaccess'),
            value: 'editaccess'
          },
          {
            icon: 'iconfont icon-operation-delete',
            label: proxy.$t('btn.delete'),
            value: 'delete',
            disabled: !btnDisabled || !window.$wujie?.props?.calcResult2('删除', [row])
          }
        ]
      };
    };
  });
  const downBtnOptions = reactive({
    type: 'text',
    iconClass: 'iconfont icon-gengduo',
    content: proxy.$t('btn.more'),
    hiddenArrow: true
  });
  /**
   * @description 当后端返回信息携带skipErr，执行该方法
   * @author czh
   * @obj 接口请求参数
   */
  const callbackError = obj => {
    const { skipErr, param } = obj;
    let message = '';
    skipErr.forEach((item, idx) => {
      if (idx === skipErr.length - 1) {
        message += `${item.message}${proxy.$t('label.continueDeleteTips')}`;
      } else {
        message += `${item.message}<br>`;
      }
    });
    proxy.$tyPlmConfirm({
      type: 'info',
      title: proxy.$t('label.continueDelete'),
      message,
      confirmButtonText: proxy.$t('btn.ok'),
      cancelButtonText: proxy.$t('btn.cancel'),
      dangerouslyUseHTMLString: true,
      beforeClose: async action => {
        if (action === 'confirm') {
          let callback = () => {
            proxy.$tyPlmMessage.success(proxy.$t('basic.message.deleteSuccessful'));
            emits('handleRefreshData');
          };
          param[0].isSkipErr = true;
          await proxy.apiFunTools.commandFunc('$pdmapis', 'part', 'postCommonDelete', param, {
            needResponseBody: true,
            callback
          });
        }
      }
    });
  };
  const handleCommand = (row, command) => {
    switch (command) {
      case 'status':
        operateCommand['setStatus'] && operateCommand['setStatus']([row]);
        emits('getCurrentRow', props.tableTypeRef, [row]);
        break;
      case 'rename':
        operateCommand['rename'] && operateCommand['rename']([row]);
        emits('getCurrentRow', props.tableTypeRef, [row]);
        break;
      case 'owner':
        operateCommand['setOwner'] && operateCommand['setOwner']([row]);
        emits('getCurrentRow', props.tableTypeRef, [row]);
        break;
      case 'process':
        window.$wujie?.bus.$emit('partReplaceRuleAddProcess', [row], wujieName);
        break;
      case 'editaccess':
        mainObj.value = row;
        editaccessShow.value = true;
        break;
      case 'delete':
        handleDeleteCurrentList({
          list: [row],
          wujieName: wujieName
        });
        break;
      default:
        break;
    }
  };
  const getMapByData = (data = [], prop = 'oid') => {
    if (!data?.length) return {};
    let map = data.reduce((total, next) => {
      total[next[prop]] = next;
      return total;
    }, {});
    return map;
  };
  return {
    btnOptions,
    isShowBtn,
    handleHyperlinkObj,
    handleCheckinObj,
    handleCheckoutObj,
    handleRevokeCheckoutObj,
    handleEditObj,
    dropdownOptions,
    downBtnOptions,
    handleCommand,
    btnLoadingMap
  };
};
